//
//  TaskWorker.m
//  e-nurse
//
//  Created by  on 4/4/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "TaskWorker.h"

@interface TaskWorker ()

@property (strong, nonatomic) NSOperationQueue *processOperationQueue;
@property (strong, nonatomic) id processTarget;
@property (assign, nonatomic) SEL processCompletedAction;
@property (strong, nonatomic) id processObject;
@property (assign, nonatomic) SEL processAction;

- (NSOperationQueue*)createProcessOperationQueue;
@end

@implementation TaskWorker
@synthesize processOperationQueue = _processOperationQueue;
@synthesize completionBlock = _completionBlock;
@synthesize processObject = _processObject;
@synthesize processCompletedAction = _processCompletedAction;
@synthesize processTarget = _processTarget;
@synthesize processAction = _processAction;

- (void)dealloc
{
    self.processOperationQueue = nil;
    self.completionBlock = nil;
    [super dealloc];
}

- (void)processActionImpl:(id)object
{
    [self.processTarget performSelector:self.processAction withObject:object];
    
    [self.processTarget performSelector:self.processCompletedAction withObject:self.processObject];
    self.processObject = nil;
    self.processTarget = nil;
}

- (void)process:(SEL)action completedAction:(SEL)completedAction target:(id)target
{
    [self processWithObject:nil action:action completedAction:completedAction target:target];
}

- (void)processWithObject:(id)object action:(SEL)action completedAction:(SEL)completedAction target:(id)target
{
    NSInvocationOperation *op= [[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(processActionImpl:) object:object] autorelease];
    
    self.processCompletedAction = completedAction;
    self.processTarget = target;
    self.processObject = object;
    self.processAction = action;
    
    NSOperationQueue *operationQueue = [self createProcessOperationQueue];
    [operationQueue addOperation:op];
}

- (NSOperationQueue*)createProcessOperationQueue
{
    if(self.processOperationQueue == nil)
    {
        self.processOperationQueue = [[[NSOperationQueue alloc] init] autorelease];
        [self.processOperationQueue setMaxConcurrentOperationCount:1];     
    }
    
    return self.processOperationQueue;    
}

@end
